package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.Dto.DishDto;
import com.itheima.Emtity.Category;
import com.itheima.Emtity.Dish;
import com.itheima.Emtity.DishFlavor;
import com.itheima.common.R;
import com.itheima.mapper.DishMapper;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 点击分类的菜品请求处理.
 */

@RestController
@RequestMapping("dish")
@Slf4j
public class DishController {
    //    写入菜品数据和菜品口味数据,是通过service.
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加新增菜品
     *
     * @param dishDto 这是一个dto类
     * @return
     */

    @PostMapping()
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.SaveDishFlavor(dishDto);
        Long categoryId = dishDto.getCategoryId();
        String key = "dish" + "_" + categoryId + "_" + 1;  //dish_139456132_1

        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品信息列表信息
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    @Transactional
    public R<Page> page(@RequestParam(required = true) int page, @RequestParam int pageSize, @RequestParam(required = false) String name) {

        // 构造分页器对象 处理page  pageSize
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

//        where处理  name

        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(name != null, Dish::getName, name);
        //添加排序条件
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行查找分页的数据.
        dishService.page(pageInfo, lambdaQueryWrapper);


        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> collect = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
//            查询的实体
            Category categoryemtity = this.categoryService.getById(categoryId);

            if (categoryemtity != null) {
                String categoryName = categoryemtity.getName();//分类名字
                dishDto.setCategoryName(categoryName);
            } else {
                //北冰洋 王老吉 没有管理他们的.
                System.out.println(categoryId);
                System.out.println(categoryemtity);
            }
            return dishDto;
        }).collect(Collectors.toList());


        dishDtoPage.setRecords(collect);
        System.out.println(dishDtoPage);
        return R.success(dishDtoPage);

    }

    /**
     * 根据id查询菜品数据和菜品口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<DishDto> get(@PathVariable long id) {
        DishDto dishDto = dishService.GetByIdWithFlavors(id);

        Long categoryId = dishDto.getCategoryId();
        String key = "dish" + "_" + categoryId + "_" + 1;  //dish_139456132_1

        redisTemplate.delete(key);
        return R.success(dishDto);
    }


    /**
     * 更新菜品数据.
     *
     * @param dishDto 这是一个dto类
     * @return
     */

    @PutMapping()
    public R<String> update(@RequestBody DishDto dishDto) {
//


        dishService.UpdateDishFlavor(dishDto);
////更新成功后,就清理所有菜品数据.使用通用方法,key dish_*
//
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
//
//        清理某个分类的数据.就要获得分类的id
//        System.out.println(dishDto);
        Long categoryId = dishDto.getCategoryId();
        String key = "dish" + "_" + categoryId + "_" + 1;  //dish_139456132_1

        redisTemplate.delete(key);


        return R.success("新增菜品成功");
    }


    /**
     * 前端传菜品分类id.需要找到菜品
     *
     * @param dish
     * @return
     */

//    @GetMapping("list")
//    public R<List<Dish>> list(Dish dish) {
//        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper();
//        lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
//        //状态是1的.表示销售状态.
//        lambdaQueryWrapper.eq(Dish::getStatus,1);
//        //根据排序
//        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        //根据分类id查询出菜品.
//        List<Dish> list = dishService.list(lambdaQueryWrapper);
//        return R.success(list);
//    }
    @GetMapping("list")
    public R<List<DishDto>> listFlavors(Dish dish) {
        List<DishDto> listDto = null;
//操作查询redis部分.
//先从redis中获取
//        动态的key.
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_139456132_1

        ValueOperations valueOperations = redisTemplate.opsForValue();
        listDto = (List<DishDto>) valueOperations.get(key);

//        如果存在,直接返回,无需查询数据库

        if (listDto != null) {
            return R.success(listDto);
        }


//操作查询数据库部分.
//        查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper();
//        根据分类查询数据
        lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //状态是1的.表示销售状态.
        lambdaQueryWrapper.eq(Dish::getStatus, 1);
        //根据排序
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //根据category_id查询出菜品.
        List<Dish> list = dishService.list(lambdaQueryWrapper);


//菜品表   -->    菜品口味表.
        listDto = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper1 = new LambdaQueryWrapper();
            lambdaQueryWrapper1.eq(DishFlavor::getDishId, id);
//获得口味表
            List<DishFlavor> list1 = dishFlavorService.list(lambdaQueryWrapper1);
//
            dishDto.setFlavors(list1);
            return dishDto;
        }).collect(Collectors.toList());


        //如果不存在,就需要查询数据库,将查询的数据放在redis.
        valueOperations.set(key, listDto, 60, TimeUnit.MINUTES);


        return R.success(listDto);
    }
}
